#include <tcp_server_client.hpp>

TcpServerClient::TcpServerClient()
	: TaskRun()
	, m_Port(0)
	, m_Socket(0)
{
	m_Buff = (char*)malloc(SOCK_BUFF_SIZE);
}

TcpServerClient::~TcpServerClient()
{
}

void TcpServerClient::StartRun(const char* ip, int port, int socket)
{
	this->m_Ip	   = ip;
	this->m_Port   = port;
	this->m_Socket = socket;

	TaskRun::Start();
}

int TcpServerClient::SendData(char* data, int size)
{
	if (data == nullptr)
	{
		return 0;
	}
	if (size <= 0)
	{
		return 0;
	}
	if (m_Socket <= 0)
	{
		Stop();
		return 0;
	}

	int wlen = send(m_Socket, data, size, 0);
	if (wlen <= 0)
	{
		Stop();
	}
	return wlen;
}

void TcpServerClient::Start(void* arg)
{
}

void TcpServerClient::Run(void* arg)
{
	while (m_IsRunning)
	{
		int rlen = recv(m_Socket, m_Buff, SOCK_BUFF_SIZE, 0);
		if (rlen <= 0)
		{
			break;
		}
		RecvData(m_Buff, rlen);
	}

	LOGI("Tcp client disconnected %d.\n", m_Socket);

	close(m_Socket);
	shutdown(m_Socket, SHUT_RDWR);
	m_Socket = 0;

	Stop();
}